package com.enzo.prms.common.interceptor;

import java.lang.reflect.Method;
import org.apache.log4j.Logger;
import com.enzo.prms.common.exception.util.ExceptionUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class ExceptionInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = -430392158034575341L;
	private static final Logger log=Logger.getLogger(ExceptionInterceptor.class);
	private static final String ERROR="error";
	

	@Override
	public String intercept(ActionInvocation arg) throws Exception {
		try {
			log.info("======================= ExceptionInterceptor start");
			return arg.invoke();
		} catch (Exception e) {
			ExceptionUtil.handlerException(e);
			setMsg(arg, "系统异常("+ExceptionUtil.getErrorCode(e)+")");
			return ERROR;
		}
	}
	
	/**
	 * get method of action
	 * @param arg
	 * @param methodName
	 * @return
	 */
	private Method getMethod(ActionInvocation arg,String methodName){
		ActionSupport action=(ActionSupport)arg.getAction();
		Method[] methods=action.getClass().getMethods();//获取action的所有public方法
		for(Method method:methods){
			if(method.getName().equals(methodName)){
				return method;
			}
		}
		return null;
	}
	
	/**
	 * setMessage
	 * @param arg
	 * @param msg
	 */
	private void setMsg(ActionInvocation arg,String msg){
		try{
			ActionSupport action=(ActionSupport)arg.getAction();
			Method setMsgMethod=getMethod(arg, "setMessage");
			setMsgMethod.invoke(action, msg);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

}
